package com.ruoyi.business.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.bo.HomeWorkStuBo;
import com.ruoyi.business.domain.vo.HomeWorkStuVo;
//import com.ruoyi.business.mapper.TQuestionMapper;
import com.ruoyi.business.domain.vo.UserVo;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.IHomeworkQuestionService;
import com.ruoyi.business.service.IHomeworkService;
import com.ruoyi.business.service.IHomeworkUserService;
import com.ruoyi.business.service.IUserService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.MailUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.oas.mappers.ExamplesMapperImpl;
import sun.security.krb5.internal.PAData;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
@Service
public class HomeworkInfoServiceImpl extends ServiceImpl<THomeworkStuMapper, THomeworkStu> implements IHomeworkService {

//    @Autowired
//    private TQuestionMapper questionMapper;

    @Autowired
    private IHomeworkQuestionService homeworkQuestionService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IHomeworkUserService homeworkUserService;

    @Autowired
    private HomeworkUserMapper homeworkUserMapper;

    @Autowired
    private HomeworkQuestionMapper homeworkQuestionMapper;

    @Autowired
    private ChapterInfoMapper chapterInfoMapper;

    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Autowired
    private MailUtils mailUtils;

    @Override
    public List<HomeWorkStuVo> getUserList(HomeWorkStuBo bo) {
//        return questionMapper.selectList(bo);
        return null;
    }

    @Override
    public TableDataInfo<HomeWorkStuVo> queryHomeworkByPage(HomeWorkStuBo bo) {
        Page<HomeWorkStuVo> page = baseMapper.selectHomeworkByPage(PageUtils.buildPage(bo), bo);
        List<HomeWorkStuVo> collect = page.getRecords().stream().map(item -> {
            if (StringUtils.isNotBlank(item.getChapterId())) {
                ChapterInfo chapterInfo = chapterInfoMapper.selectById(item.getChapterId());
                if (null != chapterInfo) {
                    item.setChapterName(chapterInfo.getName());
                }
            }
            if (StringUtils.isNotBlank(item.getCourseId())) {
                CourseInfo courseInfo = courseInfoMapper.selectById(item.getCourseId());
                if (null != courseInfo) {
                    item.setCourseName(courseInfo.getCourseName());
                }
            }
            return item;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return PageUtils.buildTableDataInfo(page);
    }

    @Override
    public HomeWorkStuVo getHomeworkById(String id) throws ParseException {
        HomeWorkStuVo vo = new HomeWorkStuVo();
        THomeworkStu homeworkStu = baseMapper.selectById(id);
        BeanUtils.copyBeanProp(vo, homeworkStu, true);
        // 查询作业题目信息
        List<String> questions = homeworkQuestionMapper.queryQuestionsByHomeworkId(id);
        vo.setQuestions(questions);

        // 查询作业班级信息
        List<String> classIds = homeworkUserMapper.queryClassIdsByHomeworkId(id);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < classIds.size(); i++) {
            sb.append(classIds.get(i));
            if (i != classIds.size() - 1) {
                sb.append(",");
            }
        }
        vo.setClassIds(sb.toString());

        // 判断当前作业的状态
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (sdf.parse(vo.getEndTime()).getTime() < new Date().getTime()) {
            vo.setStatus(false);
        }else {
            vo.setStatus(true);
        }
        return vo;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertHomeworkStu(HomeWorkStuBo bo) {
        THomeworkStu homeworkStu = new THomeworkStu();
        BeanUtils.copyBeanProp(homeworkStu, bo, true);
        // 插入班级信息
        baseMapper.insert(homeworkStu);
        // 查询班级信息
        if (StringUtils.isNotBlank(bo.getClassIds())){
            List<HomeworkUser> homeworkUsers = new ArrayList<>();
            String[] classIds = bo.getClassIds().trim().split(",");
            List<UserVo> userVos = userMapper.selectUserByClass(classIds);
            if (null != userVos) {
                List<String> emails = new ArrayList<>();
                for (UserVo userVo : userVos) {
                    HomeworkUser homeworkUser = new HomeworkUser();
                    homeworkUser.setClassId(userVo.getMyClass());
                    homeworkUser.setHomeworkId(homeworkStu.getId());
                    homeworkUser.setUserId(userVo.getUserId());
                    homeworkUsers.add(homeworkUser);
                    if (StringUtils.isNotBlank(userVo.getEmail())) {
                        emails.add(userVo.getEmail());
                    }
                }
                // 给所有学生发送邮件
                String username = SecurityUtils.getUsername();
                CourseInfo courseInfo = courseInfoMapper.selectById(bo.getCourseId());
                mailUtils.sendMessage(emails,
                        String.format("%s老师，发布了%s作业，请尽快进入系统查看", username, courseInfo.getCourseName()),
                        "课程作业");
                homeworkUserService.saveBatch(homeworkUsers);
            }
        }else {
            throw new RuntimeException("请选择班级信息");
        }
        // 插入作业和题目之间的映射关系
        List<HomeworkQuestion> homeworkQuestions = new ArrayList<>();
        if (null != bo.getQuestions() && bo.getQuestions().size() > 0) {
            for (String question : bo.getQuestions()) {
                HomeworkQuestion homeworkQuestion = new HomeworkQuestion();
                homeworkQuestion.setQid(question);
                homeworkQuestion.setHid(homeworkStu.getId());
                homeworkQuestions.add(homeworkQuestion);
            }
            homeworkQuestionService.saveBatch(homeworkQuestions);
        }
    }

    @Override
    public void updateHomeworkStu(HomeWorkStuBo bo) {
        THomeworkStu homeworkStu = new THomeworkStu();
        BeanUtils.copyBeanProp(homeworkStu, bo, true);
        baseMapper.updateById(homeworkStu);
        // 先删除映射关系
        homeworkUserService.remove(new QueryWrapper<HomeworkUser>().eq("homework_id", homeworkStu.getId()));
        homeworkQuestionService.remove(new QueryWrapper<HomeworkQuestion>().eq("hid", homeworkStu.getId()));

        // 查询班级信息
        if (StringUtils.isNotBlank(bo.getClassIds())){
            List<HomeworkUser> homeworkUsers = new ArrayList<>();
            String[] classIds = bo.getClassIds().trim().split(",");
            List<UserVo> userVos = userMapper.selectUserByClass(classIds);
            if (null != userVos) {
                for (UserVo userVo : userVos) {
                    HomeworkUser homeworkUser = new HomeworkUser();
                    homeworkUser.setClassId(userVo.getMyClass());
                    homeworkUser.setHomeworkId(homeworkStu.getId());
                    homeworkUser.setUserId(userVo.getUserId());
                    homeworkUsers.add(homeworkUser);
                }
                homeworkUserService.saveBatch(homeworkUsers);
            }
        }
        // 插入作业和题目之间的映射关系
        List<HomeworkQuestion> homeworkQuestions = new ArrayList<>();
        if (null != bo.getQuestions() && bo.getQuestions().size() > 0) {
            for (String question : bo.getQuestions()) {
                HomeworkQuestion homeworkQuestion = new HomeworkQuestion();
                homeworkQuestion.setQid(question);
                homeworkQuestion.setHid(homeworkStu.getId());
                homeworkQuestions.add(homeworkQuestion);
            }
            homeworkQuestionService.saveBatch(homeworkQuestions);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHomeworkStuById(String id) {
        baseMapper.deleteById(id);
        homeworkUserService.remove(new QueryWrapper<HomeworkUser>().eq("homework_id", id));
        homeworkQuestionService.remove(new QueryWrapper<HomeworkQuestion>().eq("hid", id));
    }
}
